package com.yachang.qym.usbhost.fragment;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.github.nkzawa.emitter.Emitter;
import com.github.nkzawa.socketio.client.IO;
import com.github.nkzawa.socketio.client.Socket;
import com.google.gson.Gson;
import com.squareup.leakcanary.RefWatcher;
import com.yachang.qym.usbhost.R;
import com.yachang.qym.usbhost.UsbApplication;
import com.yachang.qym.usbhost.activity.HelpDocActivity;
import com.yachang.qym.usbhost.activity.MachineInfoActivity;
import com.yachang.qym.usbhost.activity.TestActivity;
import com.yachang.qym.usbhost.model.CallHelpModel;
import com.yachang.qym.usbhost.model.OutPoliceModel;
import com.yachang.qym.usbhost.utils.API;
import com.yachang.qym.usbhost.utils.AllData;
import com.yachang.qym.usbhost.utils.LoadImage;
import com.yachang.qym.usbhost.utils.SendData;
import com.yachang.qym.usbhost.utils.ToastUtil;
import com.snappydb.SnappyDB;
import com.snappydb.SnappydbException;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Field;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;

import de.hdodenhof.circleimageview.CircleImageView;

import static com.yachang.qym.usbhost.utils.API.mSocket;

/**
 * Created by qym on 2015/12/21.
 */
public class MyFragment extends Fragment{
    private View mParentView ;
    //private TextView mMachineID,mMachineName,mMachineOtherName,mMachineNumber,mMachineVersion;
    private RelativeLayout mLayoutExit;
    private RelativeLayout mEnterTestModel;
    private RelativeLayout mLayoutMachineInfo,mLayoutAboutMachine,mLayoutHelpMachine,mLayoutSetting,mLayoutBugReport;
    private ProgressDialog dialog;
    private CircleImageView mIvHead;
    private TextView mTvName;
    private TextView mTvFireCompany;
    private String mFireCompanyName = "";
    private RelativeLayout mLayoutClearCache;

    private Emitter.Listener onExitPolice = new Emitter.Listener() {
        @Override
        public void call(final Object... args) {
            if(getActivity() != null) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        OutPoliceModel data = new OutPoliceModel();
                        Gson gson = new Gson();
                        JSONObject jsonObject = (JSONObject) args[0];
                        data = gson.fromJson(String.valueOf(jsonObject), OutPoliceModel.class);
                        if (data.getUid().equals(AllData.userModel.get_id())) {
                            mSocket.disconnect();
                            mSocket.off();
                            getActivity().stopService(AllData.usbIntent);
                            getActivity().finish();
                            android.os.Process.killProcess(android.os.Process.myPid());
                        }
                    }
                });
            }
        }
    };

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mParentView = inflater.inflate(R.layout.fragment_my, container, false);
        initView();
        dialog = new ProgressDialog(getActivity());
        dialog.setMessage("正在注销位置信息，请稍后。。。");
        return mParentView;
    }

    private void initView(){
        mIvHead = (CircleImageView) mParentView.findViewById(R.id.iv_head);
        mTvName = (TextView) mParentView.findViewById(R.id.tv_name);

        mLayoutMachineInfo = (RelativeLayout) mParentView.findViewById(R.id.layout_info);
        mLayoutAboutMachine = (RelativeLayout) mParentView.findViewById(R.id.layout_about_machine);
        mLayoutHelpMachine = (RelativeLayout) mParentView.findViewById(R.id.layout_help);

        mLayoutHelpMachine.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), HelpDocActivity.class);
                startActivity(intent);
            }
        });
        mLayoutSetting = (RelativeLayout) mParentView.findViewById(R.id.layout_setting);
        //mLayoutBugReport = (RelativeLayout) mParentView.findViewById(R.id.layout_bug_report);
        mLayoutMachineInfo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), MachineInfoActivity.class);
                startActivity(intent);
            }
        });

        mLayoutExit = (RelativeLayout) mParentView.findViewById(R.id.layout_exit);
        mEnterTestModel = (RelativeLayout) mParentView.findViewById(R.id.layout_enter_test_model);
        mTvFireCompany = (TextView) mParentView.findViewById(R.id.tv_fire_company);
        mLayoutClearCache = (RelativeLayout) mParentView.findViewById(R.id.layout_clear_cache);
        mLayoutClearCache.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    UsbApplication.snappydb.close();
                    UsbApplication.snappydb.destroy();
                    UsbApplication.snappydb = new SnappyDB.Builder(UsbApplication.getContext())
                            .directory(Environment.getExternalStorageDirectory().getAbsolutePath()) //optional
                            .name("yachang")//optional
                            .build();
                    ToastUtil.showToast("删除成功！");
                } catch (SnappydbException e) {
                    try {
                        UsbApplication.snappydb.destroy();
                        UsbApplication.snappydb = new SnappyDB.Builder(UsbApplication.getContext())
                                .directory(Environment.getExternalStorageDirectory().getAbsolutePath()) //optional
                                .name("yachang")//optional
                                .build();
                        ToastUtil.showToast("删除成功！");
                    } catch (SnappydbException e1) {
                        e1.printStackTrace();
                    }
                    e.printStackTrace();
                }
            }
        });
        mEnterTestModel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), TestActivity.class);
                startActivity(intent);
            }
        });
        mLayoutExit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(AllData.isNetLogin) {
                    getActivity().stopService(AllData.usbIntent);
                    getActivity().stopService(AllData.locationIntent);
                    dialog.show();
                    AllData.isInPolice = false;
                    if (AllData.needHelp) {
                        AllData.needHelp = false;
                        Map<String, Object> map = new HashMap<String, Object>();
                        map.put("id", AllData.myCallHelpModel.get_id());
                        map.put("fid", AllData.userModel.getFirecompany_id());
                        JSONObject jsonObject = new JSONObject(map);
                        mSocket.emit("cancelHelp", jsonObject);
                        SendData.data = SendData.exitNeedHelp();
                        SendData.needSend = true;

                        Map<String, Object> exitPoliceMap = new HashMap<String, Object>();
                        exitPoliceMap.put("id", AllData.outPolice_id);
                        exitPoliceMap.put("state", false);
                        exitPoliceMap.put("fid", AllData.userModel.getFirecompany_id());
                        JSONObject jsonObject1 = new JSONObject(exitPoliceMap);

                        mSocket.on("outPolice", onExitPolice);
                        mSocket.emit("outPolice", jsonObject1);
                        dialog.show();
                    } else {
                        Map<String, Object> map = new HashMap<String, Object>();
                        map.put("id", AllData.outPolice_id);
                        map.put("state", false);
                        map.put("fid", AllData.userModel.getFirecompany_id());
                        JSONObject jsonObject = new JSONObject(map);

                        mSocket.on("outPolice", onExitPolice);
                        mSocket.emit("outPolice", jsonObject);
                        dialog.show();
                    }
                } else {
                    getActivity().stopService(AllData.usbIntent);
                    getActivity().finish();
                    android.os.Process.killProcess(android.os.Process.myPid());
                }
            }
        });
        bingData();
    }

    private void bingData(){
        LoadImage.showImage(AllData.userModel.getImageUrl(), mIvHead);
        mTvName.setText(AllData.userModel.getUsername());
        if(mFireCompanyName.equals("")){
            Map<String,Object> map = new HashMap<>();
            map.put("fid", AllData.userModel.getFirecompany_id());
            map.put("state",true);
            map.put("isLogin",false);
            JSONObject jsonObject = new JSONObject(map);
            JsonObjectRequest ja = new JsonObjectRequest(Request.Method.POST, API.getFireCompany(), jsonObject, new Response.Listener<JSONObject>(){

                @Override
                public void onResponse(JSONObject response) {
                    try {
                        if (response.getInt("code") == 1){
                            if (!response.getJSONObject("result").equals(null)) {
                                mTvFireCompany.setText(response.getJSONObject("result").getString("name"));
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    ToastUtil.showToast(error.getMessage());
                    dialog.dismiss();
                }
            });
            RequestQueue queue = UsbApplication.getQueue();
            queue.add(ja);
        }else {
            mTvFireCompany.setText(mFireCompanyName);
        }
    }


    @Override
    public void onDetach() {
        super.onDetach();
        try {
            Field childFragmentManager = Fragment.class.getDeclaredField("mChildFragmentManager");
            childFragmentManager.setAccessible(true);
            childFragmentManager.set(this, null);
        } catch (NoSuchFieldException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        RefWatcher refWatcher = UsbApplication.getRefWatcher(getActivity());
        refWatcher.watch(this);
    }
}
